import React, { useState, useEffect } from 'react';
import * as actionTypes from './store/actionCreators';
import Loading from '../../baseUI/loading';
import Scroll from '../../baseUI/scroll';
import Horizen from '../../baseUI/horizen-item';
import { categoryTypes, alphaTypes } from '../../api/category';
import { NavContainer, ListContainer, List, ListItem } from './style';
import  LazyLoad, {forceCheck} from 'react-lazyload';
import {connect} from 'react-redux';
import { renderRoutes } from 'react-router-config';



// 映射Redux全局的state到组件的props上
const mapStateToProps = (state) => ({
  singerList: state.getIn(['singers', 'singerList']),
  enterLoading: state.getIn(['singers', 'enterLoading']),
  pullUploading: state.getIn(['singers', 'pullUploading']),
  pullDownLoading: state.getIn(['singers', 'pullDownLoading']),
  pageCount: state.getIn(['singers', 'pageCount']),
});

// 映射dispatch 到 props上
const mapDispatchToProps = (dispatch) => {
  return {
    getHotSingerDispatch() {
      dispatch(actionTypes.getHotSingerList())
    },

    updateDispatch(category, alpha) {
      dispatch(actionTypes.changePageCount(0));  // 由于改变了分类，所以pageCount清零
      dispatch(actionTypes.changeEnterLoading(true)); 
      dispatch(actionTypes.getSingerList(category, alpha));
    },

    // 滑到最底部刷新部分的处理
    pullUpRefreshDispatch(category, alpha, hot, count) {
      dispatch(actionTypes.changePullUpLoading(true));
      dispatch(actionTypes.changePageCount(count+1));
      if(hot){
        dispatch(actionTypes.refreshMoreHotSingerList());
      } else {
        dispatch(actionTypes.refreshMoreSingerList(category, alpha));
      }
    },

    //顶部下拉刷新
    pullDownRefreshDispatch(category, alpha) {
      dispatch(actionTypes.changePullDownLoading(true));
      dispatch(actionTypes.changePageCount(0));//属于重新获取数据
      if(category === '' && alpha === ''){
        dispatch(actionTypes.getHotSingerList());
      } else {
        dispatch(actionTypes.getSingerList(category, alpha));
      }
    }
  }
};

function Singers(props) {
  const [ category, setCategory ] = useState(''); 
  const [ alpha, setAlpha ] = useState('');

  const { singerList, enterLoading, pullUpLoading, pullDownLoading, pageCount } = props;
  const { getHotSingerDispatch, updateDispatch, pullDownRefreshDispatch, pullUpRefreshDispatch } = props;

  useEffect(() => {
    if(!singerList.size) {
      getHotSingerDispatch();
    };
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const handleUpdateCategory = (category) => {
    setCategory(category);
    updateDispatch(category, alpha);
  };

  const handleUpdateAlpha = (alpha) => {
    setAlpha(alpha);
    updateDispatch(category, alpha);
  };

  const handlePullUp = () => {
    pullUpRefreshDispatch(category, alpha, category === '', pageCount);
  };

  const handlePullDown = () => {
    pullDownRefreshDispatch(category, alpha);
  };

  const enterDetail = (id) => {
    props.history.push(`/singers/${id}`);
  };

  // 渲染函数，返回歌手列表
  const renderSingerList = () => {
    const singerListJS = singerList ? singerList.toJS() : [];
    return (
      <List>
        {
          singerListJS.map((item, index) => {
            return (
              <ListItem key={item.accountId + '-' + index} onClick={() => {enterDetail(item.id)}}>
                <div className="img_wrapper">
                  { renderRoutes(props.route.routes)}
                <LazyLoad placeholder={<img width="100%" height="100%" src={require('./singer.png')} alt="music"/>}>
                  <img src={`${item.picUrl}?param=300x300`} width="100%" height="100%" alt="music"/>
                </LazyLoad>
                </div>
                <span className="name">{item.name}</span>
              </ListItem>
            )
          })
        }
      </List>
    )
  };

  return (
    <div>
      <NavContainer>
      <Horizen 
        list={categoryTypes} 
        title="分类（默认热门）："
        handleClick={(val) => handleUpdateCategory(val)}
        oldVal={category}></Horizen>
      <Horizen 
        list={alphaTypes} 
        title="首字母："
        handleClick={(val) => handleUpdateAlpha(val)}
        oldVal={alpha}></Horizen>
      </NavContainer>
      <ListContainer>
        <Scroll 
          direction='vertical'
          pullUp={handlePullUp}
          pullDown = {handlePullDown}
          pullUpLoading = {pullUpLoading}
          pullDownLoading = {pullDownLoading}
          onScroll={forceCheck}
        >
          { renderSingerList () }
        </Scroll>
        <Loading show={enterLoading}></Loading>
      </ListContainer>
    </div>
  )
};

export default connect(mapStateToProps, mapDispatchToProps)(React.memo(Singers));

